package com.lxm.sevice.sen;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.lxm.action.ActionBase;
import com.lxm.dao.MsgMapperDao;
import com.lxm.entity.ReturnMessage;
import com.lxm.entity.SmsSenMsgEntity;
import com.lxm.entity.UserEntity;
import com.lxm.entity.query.QuerySenData;
import com.lxm.util.DateUtils;
import com.lxm.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/28 12:31
 */
@Service("WxSendMsg")
public class WxSendMsg implements senService {
    private static String senUrl="https://api.weixin.qq.com/cgi-bin/message/template/send";

    @Resource
    private RedisTemplate<String, String> auctionRedisTemplate;
    @Autowired
    private MsgMapperDao msgMapperDao;


    @Override
    public ReturnMessage sneMsg(UserEntity user , QuerySenData querySenData) {

        ValueOperations<String, String> redis = auctionRedisTemplate.opsForValue();
        String token = redis.get("token");
        JSONObject post = HttpUtils.post(senUrl + "?access_token=" + token, getTemplate(user, querySenData, querySenData.getQueryUrl()).toJSONString());
        if(post == null){
            return ActionBase.error("系统异常");
        }
        if("0".equals(post.getString("errcode"))){
            return ActionBase.success("发送成功");
        }else {
            return ActionBase.error(post.getString("errcode")+"$"+post.getString("errmsg"));
        }
    }

    public JSONObject getTemplate(UserEntity user ,QuerySenData querySenData,String url){
        JSONObject data = new JSONObject();
        data.put("touser",user.getWxOperId());
        data.put("template_id","33FxT1r8_Jo9pKgi4AogKzG3L6war9ATGRGob8ctExE");
        data.put("url",url);
        data.put("data",getData(querySenData.getTitle(),querySenData.getContent()));
        return data;
    }

    public JSONObject getData(String title,String content){
        if(content.length() > 100){
            content=content.substring(0,99)+"...";
        }
        JSONObject data = new JSONObject();
        data.put("first",new JSONObject().fluentPut("value",title));
        data.put("keyword1",new JSONObject().fluentPut("value","见后文，来自蓝小喵推送"));
        data.put("keyword2",new JSONObject().fluentPut("value", DateUtils.getCurrentMillisecondTime()));
        data.put("remark",new JSONObject().fluentPut("value", content));
        return data;
    }
}
